import { defineStore } from "pinia";
import { ref, computed } from "vue";
import {
  getConversationList,
  createConversation,
  updateConversationTitle,
  deleteConversationById,
} from "@/api/conversation";

export const useChatStore = defineStore("chat", () => {
  // 对话列表
  const conversations = ref([]);

  // 当前选中的对话ID
  const currentConversationId = ref(null);

  // 加载状态
  const loading = ref(false);

  // 分页信息
  const pagination = ref({
    page: 1,
    pageSize: 10,
    total: 0,
    pages: 0,
    hasNext: false,
    hasPrev: false,
  });

  // 是否正在加载更多
  const loadingMore = ref(false);

  // localStorage 键名
  const STORAGE_KEY = "ai-chat-current-conversation-id";

  // 保存当前对话ID到 localStorage
  const saveCurrentConversationId = (id) => {
    try {
      if (id) {
        localStorage.setItem(STORAGE_KEY, String(id));
      } else {
        localStorage.removeItem(STORAGE_KEY);
      }
    } catch (error) {
      console.error("保存当前对话ID失败", error);
    }
  };

  // 从 localStorage 恢复当前对话ID
  const restoreCurrentConversationId = () => {
    try {
      const savedId = localStorage.getItem(STORAGE_KEY);
      if (savedId) {
        const id = Number(savedId) || savedId;
        return id;
      }
    } catch (error) {
      console.error("恢复当前对话ID失败", error);
    }
    return null;
  };

  // 当前对话
  const currentConversation = computed(() => {
    return conversations.value.find(
      (conv) => conv.id === currentConversationId.value
    );
  });

  // 生成前端临时对话ID（格式：XXXX-XXXX-XXXX）
  const generateFrontendId = () => {
    const chars = '0123456789ABCDEF';
    const generateSegment = () => {
      return Array.from({ length: 4 }, () => chars[Math.floor(Math.random() * chars.length)]).join('');
    };
    return `${generateSegment()}-${generateSegment()}-${generateSegment()}`;
  };

  // 添加新对话（不再调用接口，创建临时对话）
  const addConversation = () => {
    // 检查是否有已创建的临时对话（isFront: true）且没有消息
    const existingFrontConversation = conversations.value.find(
      (conv) => conv.isFront === true && (!conv.messages || conv.messages.length === 0)
    );

    if (existingFrontConversation) {
      // 如果存在空的临时对话，自动定位到该对话
      currentConversationId.value = existingFrontConversation.id;
      saveCurrentConversationId(existingFrontConversation.id);
      return existingFrontConversation;
    }

    // 如果没有空的临时对话，创建一个新的临时对话
    const newConversation = {
      id: generateFrontendId(),
      title: "新对话",
      messages: [],
      isFront: true, // 标识为前端生成的临时对话
      createdAt: new Date(),
      updatedAt: new Date(),
    };

    // 添加到列表最前面
    conversations.value.unshift(newConversation);
    // 切换到新对话
    currentConversationId.value = newConversation.id;
    // 保存到 localStorage
    saveCurrentConversationId(newConversation.id);
    return newConversation;
  };

  // 创建后端对话（在发送第一条消息时调用）
  const createBackendConversation = async (frontendConversation) => {
    try {
      // 调用接口创建新对话
      const data = await createConversation();
      // 转换数据格式
      const backendConversation = transformConversation(data);
      
      // 更新临时对话的信息
      const index = conversations.value.findIndex(
        (conv) => conv.id === frontendConversation.id
      );
      
      if (index > -1) {
        // 保留消息，更新ID和其他信息
        conversations.value[index] = {
          ...backendConversation,
          messages: frontendConversation.messages, // 保留已有消息
          isFront: false, // 标记为已存入后端
        };
        
        // 更新当前对话ID
        currentConversationId.value = backendConversation.id;
        saveCurrentConversationId(backendConversation.id);
        
        return conversations.value[index];
      }
      
      return backendConversation;
    } catch (error) {
      console.error("创建后端对话失败", error);
      throw error;
    }
  };

  // 检查对话是否有有效的消息（用户提问和AI正确回答）
  const hasValidMessages = (conversation) => {
    if (!conversation || !conversation.messages || conversation.messages.length === 0) {
      return false;
    }
    
    // 检查是否有用户消息
    const hasUserMessage = conversation.messages.some(
      (msg) => msg.role === "user" && msg.content && msg.content.trim()
    );
    
    // 检查是否有AI消息且有内容（不是等待状态）
    const hasAiMessage = conversation.messages.some(
      (msg) => 
        (msg.role === "assistant" || msg.role === "ai") &&
        msg.content && 
        msg.content.trim() &&
        !msg.isWaiting
    );
    
    // 只有当既有用户消息又有AI消息时，才认为有有效消息
    return hasUserMessage && hasAiMessage;
  };

  // 删除对话
  const deleteConversation = async (id) => {
    try {
      // 查找要删除的对话
      const conversationToDelete = conversations.value.find(
        (conv) => conv.id === id
      );

      // 如果是前端临时对话（isFront: true），但有有效消息，也需要调用接口删除
      // 或者不是前端临时对话，也需要调用接口删除
      const shouldCallApi = 
        !conversationToDelete || 
        conversationToDelete.isFront !== true || 
        hasValidMessages(conversationToDelete);
      
      if (shouldCallApi) {
        await deleteConversationById(id);
      }

      // 从列表中移除
      const index = conversations.value.findIndex((conv) => conv.id === id);
      if (index > -1) {
        conversations.value.splice(index, 1);

        // 如果删除的是当前对话，需要切换对话
        if (currentConversationId.value === id) {
          if (conversations.value.length > 0) {
            // 切换到第一个对话
            currentConversationId.value = conversations.value[0].id;
            // 保存到 localStorage
            saveCurrentConversationId(conversations.value[0].id);
          } else {
            // 如果没有对话了，自动创建一个空白的新对话
            const newConversation = addConversation();
            // 新对话已经自动选中，不需要额外处理
          }
        }
        
        // 如果删除后对话列表为空，自动创建一个空白的新对话
        if (conversations.value.length === 0) {
          const newConversation = addConversation();
          // 新对话已经自动选中，不需要额外处理
        }
      }
    } catch (error) {
      console.error("删除对话失败", error);
      throw error;
    }
  };

  // 切换对话
  const switchConversation = (id) => {
    currentConversationId.value = id;
    // 保存到 localStorage
    saveCurrentConversationId(id);
  };

  // 更新对话ID（从临时ID更新为后端ID）
  const updateConversationId = (oldId, newId) => {
    const conversation = conversations.value.find(
      (conv) => conv.id === oldId
    );
    if (conversation && conversation.isFront === true) {
      // 更新对话ID
      conversation.id = newId;
      conversation.isFront = false; // 标记为后端对话
      
      // 如果当前选中的是旧ID，更新为新的ID
      if (currentConversationId.value === oldId) {
        currentConversationId.value = newId;
        saveCurrentConversationId(newId);
      }
      
      return true;
    }
    return false;
  };

  // 添加消息
  const addMessage = (message) => {
    const conversation = conversations.value.find(
      (conv) => conv.id === currentConversationId.value
    );
    if (conversation) {
      conversation.messages.push({
        id: Date.now(),
        ...message,
        timestamp: new Date(),
      });
      conversation.updatedAt = new Date();

      // 如果是第一条消息，更新对话标题
      if (conversation.messages.length === 1 && message.role === "user") {
        conversation.title =
          message.content.substring(0, 20) +
          (message.content.length > 20 ? "..." : "");
      }
    }
  };

  // 清空当前对话
  const clearCurrentConversation = () => {
    const conversation = conversations.value.find(
      (conv) => conv.id === currentConversationId.value
    );
    if (conversation) {
      conversation.messages = [];
      conversation.title = "新对话";
      conversation.updatedAt = new Date();
    }
  };

  // 转换后端数据格式为前端格式
  const transformConversation = (item) => {
    return {
      id: item.id,
      title: item.title || "新对话",
      messages: item.messages
        ? item.messages.map((msg, index) => ({
            id: Date.now() + index,
            role: msg.role,
            content: msg.content,
            messageType: msg.message_type,
            metadata: msg.metadata_ || {},
            timestamp: new Date(item.updated_at || item.created_at),
          }))
        : [],
      createdAt: new Date(item.created_at),
      updatedAt: new Date(item.updated_at || item.created_at),
    };
  };

  // 加载对话列表（首次加载或重置）
  const loadConversations = async () => {
    // 保存前端临时对话（isFront: true）
    const frontendConversations = conversations.value.filter(
      (conv) => conv.isFront === true
    );
    
    // 重置分页和列表（但保留前端临时对话）
    pagination.value.page = 1;
    conversations.value = frontendConversations;
    
    loading.value = true;
    try {
      const response = await getConversationList(
        pagination.value.page,
        pagination.value.pageSize
      );
      
      // 适配新的分页数据结构
      const list = response.list || [];
      const total = response.total || 0;
      const page = response.page || 1;
      const pageSize = response.page_size || 10;
      const pages = response.pages || 0;
      const hasNext = response.has_next || false;
      const hasPrev = response.has_prev || false;

      // 更新分页信息
      pagination.value = {
        page,
        pageSize,
        total,
        pages,
        hasNext,
        hasPrev,
      };

      // 转换数据格式
      const transformedList = list.map((item) => transformConversation(item));
      
      // 将前端临时对话放在最前面，然后添加后端对话
      conversations.value = [...frontendConversations, ...transformedList];

      // 如果对话列表为空，自动创建一个空白的新对话
      if (conversations.value.length === 0) {
        const newConversation = addConversation();
        // 新对话已经自动选中，不需要额外处理
        return conversations.value;
      }

      // 尝试恢复上次选中的对话
      if (conversations.value.length > 0) {
        const savedId = restoreCurrentConversationId();
        
        if (savedId) {
          // 检查保存的对话ID是否在列表中
          const savedConversation = conversations.value.find(
            (conv) => conv.id === savedId
          );
          if (savedConversation) {
            // 如果存在，恢复该对话
            currentConversationId.value = savedId;
          } else {
            // 如果匹配不到，清空保存的ID，并选择最新的一条对话
            const latestConversation = conversations.value[0];
            currentConversationId.value = latestConversation.id;
            saveCurrentConversationId(latestConversation.id);
          }
        } else {
          // 如果没有保存的对话ID，默认选中最新的一条（第一个）
          const latestConversation = conversations.value[0];
          currentConversationId.value = latestConversation.id;
          saveCurrentConversationId(latestConversation.id);
        }
      }

      return conversations.value;
    } catch (error) {
      console.error("加载对话列表失败", error);
      // 如果加载失败，且对话列表为空，自动创建一个空白的新对话
      if (conversations.value.length === 0) {
        addConversation();
      }
      throw error;
    } finally {
      loading.value = false;
    }
  };

  // 加载更多对话（下一页）
  const loadMoreConversations = async () => {
    // 如果没有下一页或正在加载，直接返回
    if (!pagination.value.hasNext || loadingMore.value || loading.value) {
      return;
    }

    loadingMore.value = true;
    try {
      // 增加页码
      pagination.value.page += 1;
      
      // 加载下一页数据
      const response = await getConversationList(
        pagination.value.page,
        pagination.value.pageSize
      );

      // 适配新的分页数据结构
      const list = response.list || [];
      const total = response.total || 0;
      const page = response.page || pagination.value.page;
      const pageSize = response.page_size || pagination.value.pageSize;
      const pages = response.pages || 0;
      const hasNext = response.has_next || false;
      const hasPrev = response.has_prev || false;

      // 更新分页信息
      pagination.value = {
        page,
        pageSize,
        total,
        pages,
        hasNext,
        hasPrev,
      };

      // 转换数据格式并追加到列表
      const transformedList = list.map((item) => transformConversation(item));
      conversations.value.push(...transformedList);

      return transformedList;
    } catch (error) {
      console.error("加载更多对话失败", error);
      // 加载失败时回退页码
      pagination.value.page -= 1;
      throw error;
    } finally {
      loadingMore.value = false;
    }
  };

  // 更新对话标题
  const updateTitle = async (conversationId, title) => {
    try {
      // 调用接口更新标题
      await updateConversationTitle(conversationId, title);
      // 更新本地数据
      const conversation = conversations.value.find(
        (conv) => conv.id === conversationId
      );
      if (conversation) {
        conversation.title = title;
        conversation.updatedAt = new Date();
      }
    } catch (error) {
      console.error("更新对话标题失败", error);
      throw error;
    }
  };

  return {
    conversations,
    currentConversationId,
    currentConversation,
    loading,
    pagination,
    loadingMore,
    addConversation,
    createBackendConversation,
    deleteConversation,
    switchConversation,
    addMessage,
    clearCurrentConversation,
    loadConversations,
    loadMoreConversations,
    updateTitle,
    updateConversationId,
  };
});
